Due to some e-mails I’ve received this week I am posting a quick tip on how to populate an ASP.NET MVC dropdownlist control using LINQ to SQL. If you haven’t read the Tip#189 about ASP.NET MVC dropdownlist controls, it is a good time to read it.
How to
Create a new ASP.NET MVC Web Application;
Right-click on the Models folder and select Add > New Item;
From the Add New Item dialog, select LINQ to SQL classes. Name it MyModel.dbml and click Add;
Select the connection you want to use on the Server Explorer Window, expand it and select the tables you want to use;
Drag and drop them onto the dbml file surface. For this example I am using a database that has two tables: Product and Category;
Right-click the Controllers folder and select Add > Controller. Name it ProductController and hit the Add button;
A new controller class is created it. Open it. We are going to add an action method called Selector that will perform a LINQ query to retrieve a list of products. We are going to save it to the ViewData dictionary and request a view to be rendered;
public class ProductController : Controller
{
MyModelDataContext _ctx = new MyModelDataContext();
public ActionResult Selector()
{
var products = from prod in _ctx.products
select prod;
ViewData[“ProductList”] = products;
return View();
}
}
Right-click the action method we’ve just created and select Add View (or just press ctrl + M, V). On the Add View dialog, name it Selector and keep the first two checkboxes unchecked. Hit the Add button;
On the View we are going to use the DropdownList HtmlHelper method to render the dropdownlist control using the list of products added to the ViewData dictionary by our Selector action method. The object used to bind an IEnumerable object to a dropdownlist control is the SelectList. There an explanation about it on Tip #189. We are going also to add a submit button so we can catch the selected item on the controller class. The Html markup will be similar to the following:
<% using (Html.BeginForm()) { %>
<%= Html.DropDownList(“lstProducts”, new SelectList((IEnumerable)ViewData[“ProductList”], “ID”, “Name”)) %>
<input type=”submit” value=”Submit” />
<% } %>
Let’s add an action method that handles the post actions on this view so we can catch the selected product id:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Selector(FormCollection form)
{
/// Gets the selected product.
int productID = Convert.ToInt32(form[“lstProducts”]);
[…]
}
Build and run the application. Navigate to http://localhost:<Port Number>/Product/Selector . The dropdownlist control is loaded and displays the product name.
You may hit the submit button and check the product id on the Selector action method that handles the post action.
It is just a simple example on how to populate the dropdownlist control using LINQ to SQL. Keep in mind that performing queries directly on the controller is not a good practice and tie your application to a specific data source is not maintainable. Check the posts below on how to make you application loosely coupled and how to create a service layer for your application:
thanks Cirilo. Keep posting.
By: janlie mcdovish on 05/24/2009
at 10:40 am
i think that in controller u must user SelectList object and then put it in ViewDate like:
ViewData[“ProductList”] = new SelectList(products, “ID”, “Name”);
and in your view simple user of dropdown like:
the main idea that u will not use any logic in your views
By: msony on 09/17/2009
at 3:29 am
Cirilo – have you any suggestion about how to show the selected item from the list in the case where this view is an Edit view?
By: Roger Maynard on 10/9/2009
at 6:20 pm
This code is really effective, I got success to populate my dropdown list perfectly.
Thank you
By: anil soni on 01/29/2010
at 3:29 pm
Thanks It was an very useful tip
By: AishuVasanth on 06/15/2010
at 1:19 pm